package com.jprocms.module.cms.controller.directive;

import com.jprocms.module.cms.controller.admin.site.vo.SiteQueryReqVO;
import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.service.site.SiteService;
import com.jprocms.module.cms.util.Freemarkers;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 站点列表 自定义标签
 *
 * @author jprocms
 */
public class SiteListDirective implements TemplateDirectiveModel {

    /**
     * 上级站点ID。长整型（Long）
     */
    private static final String PARENT_ID = "parentId";
    /**
     * 是否包含子站点。布尔型（Boolean）。默认：false
     */
    private static final String INCLUDE_CHILD = "includeChild";

    @SuppressWarnings("unchecked")
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        Freemarkers.requireLoopVars(loopVars);
        Freemarkers.requireBody(body);
        Integer parentId = Freemarkers.getInteger((TemplateModel) params.get(PARENT_ID));
        Boolean includeChild = Freemarkers.getBoolean((TemplateModel) params.get(INCLUDE_CHILD), false);
        List<SiteDO> list = siteService.getSiteList(SiteQueryReqVO.of(parentId, includeChild));
        loopVars[0] = env.getObjectWrapper().wrap(list);
        body.render(env.getOut());
    }

    private final SiteService siteService;

    public SiteListDirective(SiteService siteService) {
        this.siteService = siteService;
    }
}
